#!/bin/sh -e
#
# NVIDIA Topology Daemon Init Script
#
# Copyright (c) 2021 NVIDIA Corporation
#
# All rights reserved.  All information contained herein is proprietary and
# confidential to NVIDIA Corporation.  Any use, reproduction, or disclosure
# without the written permission of NVIDIA Corporation is prohibited.
#
# chkconfig: 2345 99 01
# description: Starts and stops the NVIDIA Topology Daemon
# processname: nvidia-topologyd
#
### BEGIN INIT INFO
# Provides:         nvidia-topologyd
# Required-Start:   $ALL
# Required-Stop:    $ALL
# Default-Start:    2 3 4 5
# Default-Stop:     0 1 6
# Description:      Starts and stops the NVIDIA Topology Daemon
### END INIT INFO


NVTD=nvidia-topologyd
NVTD_BIN=/usr/bin/${NVTD}
NVTD_RUNTIME=/var/run/${NVTD}
NVTD_PIDFILE=${NVTD_RUNTIME}/${NVTD}.pid

if [ -f ${NVTD_PIDFILE} ]; then
  read -r NVTD_PID < "${NVTD_PIDFILE}"
  # Remove stale runtime files
  if [ "${NVTD_PID}" ] && [ ! -d /proc/${NVTD_PID} ]; then
    unset NVTD_PID
  fi
fi

case "${1}" in
  start)
      echo "Starting NVIDIA Topology Daemon"

      # Execute the daemon
      ${NVTD_BIN}
      ;;
  stop)
      echo "Stopping NVIDIA Topology Daemon"

      # Stop the daemon - its PID should have been read in
      [ ! -z "${NVTD_PID}" ] && kill ${NVTD_PID} &> /dev/null
      ;;
  restart)
      $0 stop
      sleep 2
      $0 start
      ;;
  *) echo "usage: $0 {start|stop|restart}"
esac
exit 0
